<?php


namespace zqs\admin\controller;


use zqs\admin\facade\Builder;
use zqs\admin\lib\Tree;
use zqs\admin\model\Attachment;
use zqs\admin\model\AttachmentCate;

class Images extends Admin
{
    public function initialize()
    {
        parent::initialize();
        $this->model = new AttachmentCate();
        //顶级分类
        $cate_top = [0 => '顶级分类'];
        $cate_db = $this->model->where('status',1)->where('pid',0)->order('sort desc,id desc')->column('name','id');
        if ($cate_db){
            $cate_top += $cate_db;
        }
        $pid = input('id','');
        $this->form = Builder::make('form')
            ->setDataUrl('add')
            ->addFormItems([
                ['input','分类名称','name','','text','required'],
                ['select','所属分类','pid',$pid,$cate_top,'required'],
                ['input','排序','sort',0,'number','','数字越大越靠前','width:80px;']
            ])
            ->setPageTitle('分类');
    }
    public function index()
    {
        $field_name = input('field_name','');
        if (empty($field_name)) $this->error('参数错误');
        $max = input('max',1,'intval');

        //分类
        $cate_list = $this->model->where('status',1)->order('sort desc,id desc')->select()->toArray();
        Tree::instance()->init($cate_list);
        $cate_list = Tree::instance()->getTreeArray(0);
//        dump($cate_list);die;

        $this->assign('field_name',$field_name);
        $this->assign('max',$max);
        $this->assign('cate_list',$cate_list);
        return $this->fetch('images');
    }

    public function lists()
    {
        if ($this->request->isAjax()){
            list($where, $order, $page, $limit) = $this->getMap();
            $list = Attachment::where($where)->whereIn('imagetype',['png','jpg','jpeg','gif'])->page($page)->order($order);
            $cate_id = input('cate_id',0,'intval');
            if ($cate_id){
                $sonids = $this->model->where('pid',$cate_id)->column('id');
                $ids = array_merge([$cate_id],$sonids);
                $list = $list->whereIn('cate_id',$ids);
            }
            $list = $list->paginate($limit);
            $this->success('succ','',$list);
        }
    }

    /**
     * 获取分类
     */
    public function cate()
    {
        if ($this->request->isAjax()){
            //分类
            $cate_list = $this->model->where('status',1)->order('sort desc,id desc')->select()->toArray();
            Tree::instance()->init($cate_list);
            $cate_list = Tree::instance()->getTreeArray(0);
            $this->success('','',$cate_list);
        }
    }

    /**
     * 删除分类
     */
    public function delete($ids='')
    {
        if (empty($ids)) $this->error('请选择你要操作的数据');
        //是否有子类
        $cate = $this->model;
        if ($cate->where('pid',$ids)->find()){
            return $this->error('分类下有子分类，不能进行删除操作');
        }
        parent::delete();
    }

}
